<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>备件管理系统 - 入库管理</title>
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <style>
        .el-table thead th {
            background-color: #f5f5f5 !important;
        }
        .el-table tbody tr td {
            background-color: #FFFFFF !important;
        }
        .el-input-number {
            width: 100%;
        }
    </style>
</head>
<body>
<div id="app">
    <!-- 页面标题 -->
    <header class="header">
        <h2 style="margin: 0;">入库管理</h2>
    </header>

    <main>
        <!-- 退出按钮 -->
        <div style="text-align: right;">
            <el-button type="info" size="medium" @click="logout">退出</el-button>
        </div>

        <!-- 新增按钮 + 搜索框 -->
        <div style="margin-bottom: 10px; display: flex; justify-content: space-between;">
            <el-button type="primary" size="medium" @click="showAddDialog = true">新增入库记录</el-button>
            <el-button type="success" size="medium" @click="showQRCodeDialog = true">二维码操作</el-button>
            <el-input v-model="searchQuery" placeholder="请输入批次号或备件ID" style="width: 200px;"></el-input>
        </div>

        <!-- 表格 -->
        <el-table :data="paginatedInBoundRecordsList" border style="width: 100%">
            <el-table-column prop="inboundid" label="ID"></el-table-column>
            <el-table-column prop="sparepartid" label="备件ID"></el-table-column>
            <el-table-column prop="quantity" label="数量"></el-table-column>
            <el-table-column prop="batchNumber" label="批次号"></el-table-column>
            <el-table-column prop="unitPrice" label="单价"></el-table-column>
            <el-table-column prop="totalPrice" label="总价"></el-table-column>
            <el-table-column prop="date" label="日期"></el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="mini" type="danger" @click="deleteInBoundRecord(scope.row.inboundid)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
                layout="prev, pager, next"
                :total="computedInBoundRecordsList.length"
                v-model:current-page="currentPage"
                :page-size="pageSize"
                style="margin-top: 20px; justify-content: center;">
        </el-pagination>

        <!-- 新增入库记录弹窗 -->
        <el-dialog v-model="showAddDialog" title="新增入库记录" width="30%">
            <el-form :model="newInBoundRecord" label-position="left" label-width="100px">
                <el-form-item label="备件ID">
                    <el-input v-model.number="newInBoundRecord.sparepartid"></el-input>
                </el-form-item>
                <el-form-item label="数量">
                    <el-input-number v-model.number="newInBoundRecord.quantity" :min="1" @change="calculateTotalPrice"></el-input-number>
                </el-form-item>
                <el-form-item label="单价">
                    <el-input-number v-model.number="newInBoundRecord.unitPrice" :step="0.01" :min="0" @change="calculateTotalPrice" style="width: 100%"></el-input-number>
                </el-form-item>
                <el-form-item label="总价">
                    <el-input v-model.number="newInBoundRecord.totalPrice" disabled></el-input>
                </el-form-item>
                <el-form-item label="批次号">
                    <el-input v-model="newInBoundRecord.batchNumber"></el-input>
                </el-form-item>
                <el-form-item label="日期">
                    <el-date-picker v-model="newInBoundRecord.date" type="date" placeholder="选择日期" style="width: 100%;"></el-date-picker>
                </el-form-item>
                <div style="text-align: right;">
                    <el-button @click="cancelAdd">取消</el-button>
                    <el-button type="primary" @click="addInBoundRecord">添加</el-button>
                </div>
            </el-form>
        </el-dialog>

        <!-- 二维码弹窗 -->
        <el-dialog v-model="showQRCodeDialog" title="生成二维码" width="30%">
            <div style="text-align: center;">
                <img :src="qrCodeImage" alt="二维码" style="width: 200px; height: 200px;">
            </div>
            <template #footer>
                <div style="text-align: center;">
                    <el-button type="primary" @click="generateQRCode">生成二维码</el-button>
                </div>
            </template>
        </el-dialog>
    </main>

    <footer class="footer">
        &copy; 2025 备件管理系统 - 版权所有
    </footer>
</div>

<!-- 引入 Vue + Axios + Element Plus -->
<script src="https://unpkg.com/vue@3.2.36/dist/vue.global.prod.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/element-plus"></script>

<script>
    const { createApp } = Vue;

    const apiClient = axios.create({
        //本机地址
        //baseURL: 'http://localhost:8086',
        //服务器 地址
        baseURL: 'http://8.137.85.243:8086',
        timeout: 5000
    });

    const app = createApp({
        data() {
            return {
                inBoundRecordsList: [],
                newInBoundRecord: {
                    sparepartid: null,
                    quantity: 1,
                    batchNumber: '',
                    date: new Date().toISOString().split('T')[0],
                    unitPrice: 0.0,
                    totalPrice: 0.0,
                    userid: 1
                },
                searchQuery: '',
                showAddDialog: false,
                currentPage: 1,
                pageSize: 10,
                showQRCodeDialog: false,
                qrCodeImage: null
            };
        },
        computed: {
            computedInBoundRecordsList() {
                return this.inBoundRecordsList
                    .filter(record =>
                        record.batchNumber.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
                        record.sparepartid.toString().includes(this.searchQuery.toLowerCase())
                    )
                    .map((record, index) => ({
                        index: index + 1,
                        inboundid: record.inboundid,
                        sparepartid: record.sparepartid,
                        quantity: record.quantity,
                        batchNumber: record.batchNumber,
                        date: record.date,
                        unitPrice: record.unitPrice ? record.unitPrice.toFixed(2) : '暂无',
                        totalPrice: record.totalPrice ? record.totalPrice.toFixed(2) : '暂无'
                    }));
            },
            paginatedInBoundRecordsList() {
                const start = (this.currentPage - 1) * this.pageSize;
                const end = start + this.pageSize;
                return this.computedInBoundRecordsList.slice(start, end);
            }
        },
        mounted() {
            this.loadInBoundRecords();
        },
        methods: {
            calculateTotalPrice() {
                if (this.newInBoundRecord.quantity && this.newInBoundRecord.unitPrice) {
                    this.newInBoundRecord.totalPrice = (this.newInBoundRecord.quantity * this.newInBoundRecord.unitPrice).toFixed(2);
                } else {
                    this.newInBoundRecord.totalPrice = 0.0;
                }
            },
            async loadInBoundRecords() {
                try {
                    const res = await apiClient.get('/api/inboundrecords/listall');
                    const records = res.data;

                    // 加载批次管理信息
                    this.inBoundRecordsList = await Promise.all(records.map(async (record) => {
                        try {
                            const batchRes = await apiClient.get(`/api/batchmanagement/findbybatchnumber/${record.batchNumber}`);
                            const batchData = batchRes.data || {};
                            return {
                                inboundid: record.inboundid,
                                sparepartid: record.sparepartid,
                                quantity: record.quantity,
                                batchNumber: record.batchNumber,
                                date: record.date,
                                unitPrice: batchData.unitPrice,
                                totalPrice: batchData.totalPrice
                            };
                        } catch (err) {
                            console.error(`加载批次 ${record.batchNumber} 失败`, err);
                            return {
                                inboundid: record.inboundid,
                                sparepartid: record.sparepartid,
                                quantity: record.quantity,
                                batchNumber: record.batchNumber,
                                date: record.date,
                                unitPrice: '暂无',
                                totalPrice: '暂无'
                            };
                        }
                    }));
                } catch (err) {
                    alert('加载入库记录失败: ' + err.message);
                }
            },
            async addInBoundRecord() {
                if (!this.newInBoundRecord.sparepartid ||
                    !this.newInBoundRecord.quantity ||
                    !this.newInBoundRecord.batchNumber ||
                    !this.newInBoundRecord.unitPrice) {
                    alert('请填写完整信息（备件ID、数量、批次号、单价）');
                    return;
                }

                try {
                    // 插入入库记录
                    const inBoundRes = await apiClient.post('/api/inboundrecords/insert', {
                        sparepartid: this.newInBoundRecord.sparepartid,
                        quantity: this.newInBoundRecord.quantity,
                        batchNumber: this.newInBoundRecord.batchNumber,
                        date: this.newInBoundRecord.date,
                        userid: this.newInBoundRecord.userid
                    });

                    // 插入批次管理记录
                    await apiClient.post('/api/batchmanagement/insert', {
                        sparepartid: this.newInBoundRecord.sparepartid,
                        quantity: this.newInBoundRecord.quantity,
                        batchNumber: this.newInBoundRecord.batchNumber,
                        entryDate: this.newInBoundRecord.date,
                        unitPrice: parseFloat(this.newInBoundRecord.unitPrice),
                        totalPrice: parseFloat(this.newInBoundRecord.totalPrice)
                    });

                    // 重置表单
                    this.newInBoundRecord = {
                        sparepartid: null,
                        quantity: 1,
                        batchNumber: '',
                        date: new Date().toISOString().split('T')[0],
                        unitPrice: 0.0,
                        totalPrice: 0.0,
                        userid: 1
                    };
                    this.showAddDialog = false;
                    this.loadInBoundRecords();
                } catch (err) {
                    alert('新增入库或批次管理失败: ' + err.message);
                    console.error('新增失败:', err);
                }
            },
            cancelAdd() {
                this.newInBoundRecord = {
                    sparepartid: null,
                    quantity: 1,
                    batchNumber: '',
                    date: new Date().toISOString().split('T')[0],
                    unitPrice: 0.0,
                    totalPrice: 0.0,
                    userid: 1
                };
                this.showAddDialog = false;
            },
            async deleteInBoundRecord(id) {
                if (!confirm('确定删除？')) return;
                await apiClient.delete(`/api/inboundrecords/delete/${id}`);
                this.loadInBoundRecords();
            },
            async generateQRCode() {
                const url = 'http://8.137.85.243:8086/contact/inbound_records.html';
                this.$notify({ title: '提示', message: '正在生成二维码...', duration: 2000 });

                try {
                    const res = await apiClient.get('/api/qrcode/generate', {
                        params: { content: url }
                    });
                    this.qrCodeImage = res.data;
                    this.$notify({ title: '成功', message: '二维码生成成功！', type: 'success', duration: 2000 });
                } catch (err) {
                    this.$notify.error({ title: '错误', message: '二维码生成失败: ' + err.message, duration: 3000 });
                }
            },
            logout() {
                window.location.href = '/operator.html';
            }
        }
    });

    app.use(ElementPlus);
    app.mount('#app');
</script>
</body>
</html>
